//index.js
//获取应用实例
var app = getApp();
var WxParse = require('../../templates/wxParse/wxParse.js');
var md5 = require("../../utils/md5.js");
Page({
  data: {
    autoplay: true,
    interval: 3000,
    duration: 1000,
    goodsDetail: {},
    swiperCurrent: 0,
    hasMoreSelect: false,
    selectSize: "选择：",
    selectSizePrice: 0,
    shopNum: 0,
    hideShopPopup: true,
    buyNumber: 1,
    buyNumMin: 1,
    buyNumMax: 0,
    reputation: [],
    shopDeliveryPrice: 0,
    propertyChildIds: "",
    propertyChildNames: "",
    canSubmit: false, //  选中规格尺寸时候是否允许加入购物车
    shopCarInfo: {},
    shopType: "addShopCar", //购物类型，加入购物车或立即购买，默认为加入购物车
    imgheights:[],
    imgWidth:750
  },

  //事件处理函数
  swiperchange: function(e) {
    //console.log(e.detail.current)
    this.setData({
      swiperCurrent: e.detail.current
    })
  },
  onLoad: function(e) {
    wx.showLoading({
      title: '加载中...',
    })

    var that = this;
    var scene = decodeURIComponent(e.scene);
    if (scene != 'undefined' && scene != undefined){
      scene = scene.split("=");
      var product_id = scene[1];
    }else{
      var product_id = "" + e.id;
    }
    if (e.openid != undefined && e.user_id != undefined) {
      app.globalData.openId = e.openid
      app.globalData.userId = e.user_id
      wx.setStorageSync('openId', e.openid);
      wx.setStorageSync('userId', e.user_id);
      console.log('商品取openid：' + e.openid)
    }
    
    that.editLand();
    that.getNum();
    var openid = app.globalData.openId;
    var user_id = app.globalData.userId;
    //注册上级
    if (e.share != undefined){
      console.log(e);
      console.log(e.share);
      if (e.share != openid){
        console.log('注册上级');
        wx.request({
          url: app.globalData.serviceUrl + 'Product.ShareRelation',
          header: {
            'Content-Type': 'json'
          },
          data: {
            sign: md5.md5(openid + 'Product.ShareRelation' + e.share + user_id),
            user_id: user_id,
            openid: openid,
            share_openid: e.share,
          },
          success: function (res) {}
        });
      }
    }
    
    var service = 'Product.GetInfo';
    var sign = md5.md5(openid + product_id + service + user_id + '2');
    wx.request({
      url: app.globalData.serviceUrl + 'Product.GetInfo',
      header: {
        'Content-Type': 'json'
      },
      data: {
        sign: sign,
        user_id: user_id,
        openid: openid,
        product_id: product_id,
        view_type:'2',
      },
      success: function(res) {
        wx.hideLoading();
        var result = res.data.data;
        if (result.code == 0) {
          var info = result.info;
          var picture = []
          if (info) {
            console.log(info);
            for (var i = 0; i < info.picture.length; i++) {
              picture.push(info.picture[i]);
            }
          }
          console.log(picture.length);
          if (picture.length == 0) {
            console.log(info);
            picture.push(info.product_picture);
          }

          info.picture = picture;
          console.log(info);
          that.setData({
            goodsDetail: info,
            productId: product_id,
          });
          var shop_id = info.shop_id;
          app.globalData.shopId = shop_id;
          wx.setStorageSync('shop_id', shop_id)
          WxParse.wxParse('article', 'html', info.product_content, that, 5);
          app.globalData.shopPic = info.shop_pic_small;
          app.globalData.shopName = info.shop_name;
        }
      },
      complete: function(res) {
        console.log(res);
        var statusCode = res.statusCode;
        if (statusCode == 502){
          wx.showModal({
            title: '提示',
            content: '网络异常',
            showCancel: false
          })
          return;
        }
      },
      fail: function () {
        //请求超时提示
        wx.showModal({
          title: '提示',
          content: '网络异常',
          showCancel: false
        })
        return;
      }
    })
    that.reputation(e.id);
    wx.getSystemInfo({
      success: function (res) {
        console.log(res.windowWidth)
        console.log(res.windowHeight)
        that.setData({
          imgWidth:res.windowWidth
        })

      }
    })
  },
  goShopCar: function() {
    wx.reLaunch({
      url: "/pages/shop-cart/index"
    });
  },
  toAddShopCar: function() {
    this.setData({
      shopType: "addShopCar"
    })
    this.bindGuiGeTap();
  },
  tobuy: function() {
    console.log(app.globalData)
    if (!app.globalData.userId || !app.globalData.openId) {
      wx.navigateTo({
        url: "/pages/login/index"
      })
      return;
    }
    this.setData({
      shopType: "tobuy"
    });
    this.bindGuiGeTap();
    /*    if (this.data.goodsDetail.properties && !this.data.canSubmit) {
          this.bindGuiGeTap();
          return;
        }
        if(this.data.buyNumber < 1){
          wx.showModal({
            title: '提示',
            content: '暂时缺货哦~',
            showCancel:false
          })
          return;
        }
        this.addShopCar();
        this.goShopCar();*/
  },
  /**
   * 规格选择弹出框
   */
  bindGuiGeTap: function() {
    this.setData({
      hideShopPopup: false
    })
  },
  /**
   * 规格选择弹出框隐藏
   */
  closePopupTap: function() {
    this.setData({
      hideShopPopup: true
    })
  },

//  imageLoad: function (e) {
//    //获取图片真实宽度
//    var imgwidth = e.detail.width,
//      imgheight = e.detail.height,
//      //宽高比
//      ratio = imgwidth / imgheight;
//    console.log(imgwidth, imgheight)
//   //计算的高度值
//    var viewHeight = this.data.imgWidth / ratio;
//    var imgheight = viewHeight
//    var imgheights = this.data.imgheights
//    //把每一张图片的高度记录到数组里
//    imgheights.push(imgheight)
//    this.setData({
//      imgheights: imgheights,
//    })
//
//    console.log(123456)
//    console.log(imgheight)
//  },
  numJianTap: function() {
    if (this.data.buyNumber > this.data.buyNumMin) {
      var currentNum = this.data.buyNumber;
      currentNum--;
      this.setData({
        buyNumber: currentNum
      })
    }
  },
  numJiaTap: function() {
    //if (this.data.buyNumber < this.data.buyNumMax) {
    var currentNum = this.data.buyNumber;
    currentNum++;
    this.setData({
      buyNumber: currentNum
    })
  },
  /**
   * 选择商品规格
   * @param {Object} e
   */
  labelItemTap: function(e) {
    var that = this;
    // 取消该分类下的子栏目所有的选中状态
    var childs = that.data.goodsDetail.properties[e.currentTarget.dataset.propertyindex].childsCurGoods;
    for (var i = 0; i < childs.length; i++) {
      that.data.goodsDetail.properties[e.currentTarget.dataset.propertyindex].childsCurGoods[i].active = false;
    }
    // 设置当前选中状态
    that.data.goodsDetail.properties[e.currentTarget.dataset.propertyindex].childsCurGoods[e.currentTarget.dataset.propertychildindex].active = true;
    // 获取所有的选中规格尺寸数据
    var needSelectNum = that.data.goodsDetail.properties.length;
    var curSelectNum = 0;
    var propertyChildIds = "";
    var propertyChildNames = "";
    for (var i = 0; i < that.data.goodsDetail.properties.length; i++) {
      childs = that.data.goodsDetail.properties[i].childsCurGoods;
      for (var j = 0; j < childs.length; j++) {
        if (childs[j].active) {
          curSelectNum++;
          propertyChildIds = propertyChildIds + that.data.goodsDetail.properties[i].id + ":" + childs[j].id + ",";
          propertyChildNames = propertyChildNames + that.data.goodsDetail.properties[i].name + ":" + childs[j].name + "  ";
        }
      }
    }
    var canSubmit = false;
    if (needSelectNum == curSelectNum) {
      canSubmit = true;
    }
    that.setData({
      goodsDetail: that.data.goodsDetail,
      canSubmit: canSubmit
    })
  },
  /**
   * 加入购物车
   */
  addShopCar: function() {
    if (this.data.goodsDetail.properties && !this.data.canSubmit) {
      if (!this.data.canSubmit) {
        wx.showModal({
          title: '提示',
          content: '请选择商品规格！',
          showCancel: false
        })
      }
      this.bindGuiGeTap();
      return;
    }
    if (this.data.buyNumber < 1) {
      wx.showModal({
        title: '提示',
        content: '购买数量不能为0！',
        showCancel: false
      })
      return;
    }
    if (!app.globalData.userId || !app.globalData.openId) {
      wx.navigateTo({
        url: "/pages/login/index"
      })
      return;
    }
    var that = this;
    var openid = app.globalData.openId;
    var product_id = that.data.productId;
    var product_num = that.data.buyNumber;
    var service = 'Product.AddShopCart';
    var user_id = app.globalData.userId;
    var sign = md5.md5(openid + product_id + product_num + service + user_id);
    wx.request({
      url: app.globalData.serviceUrl + 'Product.AddShopCart',
      header: {
        'Content-Type': 'json'
      },
      data: {
        openid: openid,
        product_id: product_id,
        product_num: product_num,
        sign: sign,
        user_id: user_id,
      },
      success: function(res) {
        var result = res.data.data;
        console.log(result);
        if (result.code == 0) {
          wx.showToast({
            title: '加入购物车成功',
            icon: 'success',
            duration: 2000
          })
          that.getNum();
        } else {
          wx.showToast({
            title: result.msg,
            icon: 'success',
            duration: 2000
          })
        }
      }
    })
  },
  /**
   * 立即购买
   */
  buyNow: function() {
    var that = this;
    if (this.data.goodsDetail.properties && !this.data.canSubmit) {
      if (!this.data.canSubmit) {
        wx.showModal({
          title: '提示',
          content: '请选择商品规格！',
          showCancel: false
        })
      }
      this.bindGuiGeTap();
      wx.showModal({
        title: '提示',
        content: '请先选择规格尺寸哦~',
        showCancel: false
      })
      return;
    }
    if (this.data.buyNumber < 1) {
      wx.showModal({
        title: '提示',
        content: '购买数量不能为0！',
        showCancel: false
      })
      return;
    }
    if (this.data.selectSizePrice * this.data.buyNumber < this.data.shopDeliveryPrice) {
      wx.showModal({
        title: '未达到起送价',
        content: '请您再选一些吧！',
        showCancel: false,
      })
    } else {
      //组建立即购买信息
      wx.showToast({
        title: '加载中',
        icon: 'loading'
      })
      var buyNowInfo = this.buliduBuyNowInfo();
      //获取最新价格进行校验
      var openid = app.globalData.openId;
      var product_id = buyNowInfo.goodsId;
      var service = 'Product.GetInfo';
      var user_id = app.globalData.userId;
      var sign = md5.md5(openid + product_id + service + user_id);
      wx.request({
        url: app.globalData.serviceUrl + 'Product.GetInfo',
        header: {
          'Content-Type': 'json'
        },
        data: {
          openid: openid,
          product_id: product_id,
          sign: sign,
          user_id: user_id,
        },
        success: function(res) {
          var result = res.data.data;
          if (result.code == 0) {
            wx.hideToast()
            if (result.info.product_money != buyNowInfo.price) {
              wx.showModal({
                title: '提示',
                content: result.info.product_name + ' 价格有调整，请重新购买',
                showCancel: false
              })
              return;
            }
          }
        },
        complete: function(res) {
          wx.hideToast()
          console.log(res);
        },
      })

      var openid = app.globalData.openId;
      var product_id = buyNowInfo.goodsId;
      var price = buyNowInfo.price;
      var number = buyNowInfo.number;
      var current_shop_id = app.globalData.shopId;
      var service = 'Product.Buy';
      var user_id = app.globalData.userId;
      var buy_num = that.data.buyNumber;
      var xcx = 'xcx';
      var sign = md5.md5(buy_num + current_shop_id + openid + product_id + service + user_id + xcx);
      wx.request({
        url: app.globalData.serviceUrl + 'Product.Buy',
        header: {
          'Content-Type': 'json'
        },
        data: {
          sign: sign,
          user_id: user_id,
          openid: openid,
          product_id: product_id,
          current_shop_id: current_shop_id,
          buy_num: buy_num,
          xcx:xcx
        },
        success: function(res) {
          wx.hideToast()
          that.closePopupTap();
          var result = res.data.data;
          if (result.code == 0) {
            buyNowInfo.shop_id = app.globalData.shopId;
            buyNowInfo.order_id = result.info.order_id;
            buyNowInfo.order_num = result.info.order_num;
            buyNowInfo.shop_address = result.info.shop_address;
            buyNowInfo.shop_worktime = result.info.shop_worktime;
            buyNowInfo.user_tel = result.info.user_tel;
            buyNowInfo.is_delive = result.info.is_delive;
            buyNowInfo.is_dada = result.info.is_dada;
            buyNowInfo.dada_city_code = result.info.dada_city_code;
            buyNowInfo.delive_fee = result.info.delive_fee;
            //buyNowInfo.total_price = result.info.total_price;
            buyNowInfo.default_address = result.info.default_address;
            buyNowInfo.is_canhe_dis = result.info.is_canhe_dis;
            buyNowInfo.is_peisong_dis = result.info.is_peisong_dis;
            buyNowInfo.canhe_money = result.info.canhe_money;
            buyNowInfo.message = result.info.message;
            wx.setStorageSync('buyNowInfobbc', buyNowInfo);
            console.log(buyNowInfo);
            console.log(wx.getStorageSync('buyNowInfobbc'))
            console.log('缓存')
            wx.navigateTo({
              url: "/pages/to-pay-order/index?orderType=buyNow"
            })
          } else {
            wx.showModal({
              title: '失败',
              content: result.msg,
              showCancel: false
            })
          }
        },
        complete: function(res) {
          console.log(res);
          wx.hideToast()
          that.closePopupTap();
        },
      })
    }
  },

  buliduBuyNowInfo: function() {
    var shopCarMap = {};
    shopCarMap.goodsId = this.data.productId;
    shopCarMap.pic = this.data.goodsDetail.product_picture;
    shopCarMap.name = this.data.goodsDetail.product_name;
    shopCarMap.price = this.data.goodsDetail.product_money;
    shopCarMap.number = this.data.buyNumber;
    shopCarMap.total = parseFloat((parseFloat(shopCarMap.price) * shopCarMap.number).toFixed(2));
    shopCarMap.total_price = parseFloat((parseFloat(shopCarMap.price) * shopCarMap.number).toFixed(2));
    shopCarMap.shopNum = 0;
    return shopCarMap;
  },
  onShareAppMessage: function() {
    var that = this
    var title = '';
    that.zhuanfa();
    console.log('/pages/goods-details/index?id=' + that.data.productId + '&inviter_id=' + wx.getStorageSync('uid') + '&share=' + app.globalData.openId);
    if (that.data.goodsDetail.share_title == ''){
      title = that.data.goodsDetail.product_name;
    }else{
      title = that.data.goodsDetail.share_title; 
    }
    var share = {
      title: title,
      path: '/pages/goods-details/index?id=' + that.data.productId + '&inviter_id=' + wx.getStorageSync('uid') + '&share=' + app.globalData.openId,
      imageUrl: that.data.goodsDetail.picture[0],
      success: function (res) {
        wx.showToast({
          title: '转发成功'
        })
      },
      fail: function (res) {

      }
    }
    return share
  },

  zhuanfa:function(){
    var that = this;
    var sign = md5.md5(that.data.productId + app.globalData.openId + 'System.ZhuanFa' + app.globalData.userId + '2' + 'product');
    wx.request({
      url: app.globalData.serviceUrl + 'System.ZhuanFa',
      header: {
        'Content-Type': 'json'
      },
      data: {
        sign: sign,
        user_id: app.globalData.userId,
        open_id: app.globalData.openId,
        data_id: that.data.productId,
        zhuanfa_type: 'product',
        zhuanfa_laiyuan:'2',
      },
      success: function (res) {

      }
    })
  },

  reputation: function(goodsId) {
    var that = this
    var openid = app.globalData.openId;
    var user_id = app.globalData.userId;
    var product_id = goodsId;
    var page = 1;
    var page_count = 20;
    var service = 'Product.GetproductPinglun';
    var sign = md5.md5(openid + page + page_count + product_id + service + user_id);
    wx.request({
      url: app.globalData.serviceUrl + 'Product.GetproductPinglun',
      header: {
        'Content-Type': 'json'
      },
      data: {
        sign: sign,
        user_id: user_id,
        openid: openid,
        product_id: product_id,
        page: page,
        page_count: page_count
      },
      success: function(res) {
        var result = res.data.data;
        if (result.code == 0) {
          var pinglun = res.data.data.info;
          if (pinglun.length > 0) {
            for (var i = 0; i < pinglun.length; i++) {
              if (pinglun[i].pinglun_picture.length > 0) {
                var pinglun_img = pinglun[i].pinglun_picture;
                var pinglun_img_array = [];
                for (var a = 0; a < pinglun_img.length; a++) {
                  pinglun_img_array.push(pinglun_img[a].imgurl);
                }
                pinglun[i].pinglun_picture = pinglun_img_array;
              }
            }
          }
          console.log(pinglun);
          that.setData({
            reputation: pinglun
          });
        }
      }
    })
  },
  getNum: function() {
    var that = this;
    var openid = app.globalData.openId;
    var shop_id = app.globalData.shopId;;
    var user_id = app.globalData.userId;
    var service = 'Product.GetShopCart';
    var sign = md5.md5(openid + service + shop_id + user_id);
    wx.request({
      url: app.globalData.serviceUrl + 'Product.GetShopCart',
      header: {
        'Content-Type': 'json'
      },
      data: {
        openid: openid,
        shop_id: shop_id,
        sign: sign,
        user_id: user_id,
      },
      success: function(res) {
        console.log(res);
        var code = res.data.data.code;
        var shopList = [];
        if (code == 0) {
          var info = res.data.data.info;
          if (info[0].product) {
            shopList = info[0].product;
          }
        }
        that.setData({
          shopNum: shopList.length,
          hideShopPopup: true
        })
      }
    })
  },

  editLand: function() {
    var service = 'User.EditLand';
    var open_id = app.globalData.openId;
    var user_id = app.globalData.userId;
    var pid = 1;
    var sign = md5.md5(open_id + pid + service + user_id);
    wx.request({
      url: app.globalData.serviceUrl + service,
      header: {
        'Content-Type': 'json'
      },
      data: {
        sign: sign,
        user_id: user_id,
        open_id: open_id,
        pid: pid,
      },
      success: (res) => {
        var result = res.data.data;
        if (result.code == 0) {
          if (result.info == 1) {
            console.log('登陆成功，1111111')
          }
        }
      }
    })
  },

  imgYu: function (e) {//图片预览
    console.log(e);
    var src = e.currentTarget.dataset.src;//获取data-src
    var imgList = e.currentTarget.dataset.list;//获取data-list
    //图片预览
    wx.previewImage({
      current: src, // 当前显示图片的http链接
      urls: imgList // 需要预览的图片http链接列表
    })
  },
})